using System;
using System.Globalization;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Web.UI.WebControls.WebParts;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.Utilities;

using Microsoft.SharePoint.BusinessData.SharedService;
using Microsoft.SharePoint.BusinessData.MetadataModel;
using Microsoft.BusinessData.MetadataModel;



namespace $safeprojectname$.Features.Feature1
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("c2c86185-1fe3-4e47-b812-ee3b96fc8bfa")]
    public class Feature1EventReceiver : SPFeatureReceiver
    {
        internal static class Constants
    {
        internal const string LeftZoneWebPartZoneID = "ZoneLeft";
        //internal const string LeftWebPartZoneID = "Left";
        internal const string DefaultPage = "default.aspx";
        internal const string Entity = "Entity";
        internal const string EntityNamespace = "EntityNamespace";
        internal const string ShowInECBtrue = "ShowInECB=true";
        internal const string ListActionName = "BDC.URL.{0}";
        
    }

         [Microsoft.SharePoint.Security.SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
          
            if (properties == null)
            {
                throw new System.ArgumentNullException("properties");
            }

            base.FeatureActivated(properties);

            try
            {
                SPWeb centerWeb = (SPWeb)properties.Feature.Parent;
                uint currentLCID = centerWeb.Language;

                SPFile file = centerWeb.GetFile(SPUrlUtility.CombineUrl(centerWeb.Url, Constants.DefaultPage));

                string externalListTitle = "$entityNameproperty$";
                SPList externalList = centerWeb.Lists[externalListTitle]; // Customers list created from element manifest of dependent feature
                externalList.OnQuickLaunch = true;
                externalList.Update();
                
                using (SPLimitedWebPartManager webPartManager = file.GetLimitedWebPartManager(PersonalizationScope.Shared))
                {
                    XsltListViewWebPart initialWebPart = GetXsltListViewWebPart(webPartManager, externalListTitle);
                    XsltListViewWebPart externalListWebPart = CreateXsltListViewWebPart(externalList, externalListTitle);
                    webPartManager.AddWebPart(externalListWebPart, Constants.LeftZoneWebPartZoneID, 0);

                    if (null != initialWebPart)
                    {
                        webPartManager.DeleteWebPart(initialWebPart);
                    }

                    file.Update();

                };

                //Trim the custom actions other than 'Open Workspace' from the given external list
                TrimNonOpenWorkspaceActions(centerWeb, externalList);

                centerWeb.Update();
               }
            catch (Exception e)
            {
                throw;
            }

        }

         internal static void TrimNonOpenWorkspaceActions(SPWeb web, SPList externalList)
        {
             string entity = externalList.DataSource.GetProperty(Constants.Entity);
            string entityNS = externalList.DataSource.GetProperty(Constants.EntityNamespace);
            // get the entity inforamtion, extract the action names for the Run Report form
            BdcService bdc = Microsoft.SharePoint.Administration.SPFarm.Local.Services.GetValue<BdcService>(String.Empty);
            DatabaseBackedMetadataCatalog catalog = bdc.GetDatabaseBackedMetadataCatalog(SPServiceContext.GetContext(web.Site));
            IEntity ent = catalog.GetEntity(entityNS, entity);
            List<string> toBeDeletedActions = new List<string>();
            foreach (System.Collections.Generic.KeyValuePair<string, Microsoft.BusinessData.MetadataModel.IAction> nameActionPair in ent.GetActions())
            {
                IAction action = nameActionPair.Value;
                // URL should contain "ShowInECB=true" to not be trimmed.
                string actionUrl = action.Url;
                if (actionUrl.IndexOf(Constants.ShowInECBtrue, StringComparison.OrdinalIgnoreCase) == -1)
                {
                    toBeDeletedActions.Add(action.Name);
                }
            }
            foreach (string toBeDeletedActioName in toBeDeletedActions)
            {
                string listActionName = string.Format(CultureInfo.InvariantCulture, Constants.ListActionName, toBeDeletedActioName);
                foreach (SPUserCustomAction action in externalList.UserCustomActions)
                {
                    if (action.Scope == SPUserCustomActionScope.List
                    && listActionName.Equals(action.Name, StringComparison.Ordinal))
                    {
                        action.Delete();
                        break;
                    }
                }
            }
            // update the list
            externalList.Update();
        }
                                                    
 
         internal static XsltListViewWebPart CreateXsltListViewWebPart(SPList list, string listTitle)
        {
          
            XsltListViewWebPart listWebPart = new XsltListViewWebPart();

            listWebPart.Title = listTitle;
            listWebPart.ListName = list.ID.ToString("B").ToUpper(CultureInfo.InvariantCulture);
            listWebPart.ViewGuid = list.Views[0].ID.ToString();
            return listWebPart;
        }

        static XsltListViewWebPart GetXsltListViewWebPart(SPLimitedWebPartManager webPartManager, string listTitle)
        {
           XsltListViewWebPart listViewWebPart = null;

           foreach (Microsoft.SharePoint.WebPartPages.WebPart xlvwp in webPartManager.WebParts)
            {
                if (String.Equals(xlvwp.Title, listTitle))
                {
                    listViewWebPart = (XsltListViewWebPart)xlvwp;
                    break;
                }
            }
            return listViewWebPart;
        }

        // Uncomment the method below to handle the event raised after a feature has been activated.

        //public override void FeatureActivated(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is deactivated.

        //public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}
    }
}
